package com.wonders.ghy.juc.死锁;

import java.util.concurrent.TimeUnit;

/**
 * 死锁只是两个或两个以上的进程在执行过程中，
 * 引争抢资源而造成的一种相互等待的现象，
 * 若无外力干涉那它们都将无法退进下去
 */
public class DeadLockDemo {
    public static void main(String[] args) {
        new Thread(new HoldLockThread("lockA","lockB"),"AA").start();
        new Thread(new HoldLockThread("lockB","lockA"),"BB").start();
    }
}
class HoldLockThread implements Runnable{
    private String lockA;
    private String lockB;

    public HoldLockThread(String lockA, String lockB) {
        this.lockA = lockA;
        this.lockB = lockB;
    }

    @Override
    public void run() {
        synchronized (lockA){
            System.out.println("线程："+Thread.currentThread().getName()+"持有"+lockA+"锁"+"，尝试获取"+lockB+"锁");
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (lockB){
                System.out.println("线程："+Thread.currentThread().getName()+"持有"+lockB+"锁"+"，尝试获取"+lockA+"锁");
            }
        }

    }
}